package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;

import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Override
    @Transactional//因为多次执行添加事务统一
    //用户下单
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

//TODO 1、下单数据校验（收货地址为空、超出配送范围、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());//根据方法获取购物车数据
        if (addressBook == null){//判断数据是否为空
            //直接抛出异常说收货地址为空
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();//获取当前下单用户id
        ShoppingCart shoppingCart = new ShoppingCart();//创建购物车对象
        shoppingCart.setUserId(userId);
        //查询当前购物车数据并进行判断
        List<ShoppingCart> cartList = shoppingCartMapper.list(shoppingCart);//获取购物车数据 查询到多条数据
        if (cartList == null && cartList.size() ==0){//判断查询的数据并判断不行就直接返回错误提示信息
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //TODO 2、构造订单数据
        //从ordersSubmitDTO中拷贝订单信息
        //根据地址簿设置订单配送信息
        Orders orders = new Orders();//通过判断说明有订单生成订单信息
        BeanUtils.copyProperties(ordersSubmitDTO,orders);//拷贝数据
        orders.setPhone(addressBook.getPhone());//添加一些基本信息 根据获取到的购物车信息进行添加
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());

        //TODO 3、向订单表orders插入1条数据
        orderMapper.insert(orders);
        //TODO 4、保存订单明细order_detail数据
        List<OrderDetail> orderDetailList = new ArrayList<>();//创建一个集合 进行订单的储存 以便后面sql语句进行批量添加  也可写在循环中分次添加
        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);
        //TODO 5、下单成功，清理购物车中的数据
        shoppingCartMapper.deleteByUserId(userId);
        //TODO 6、封装返回结果
        OrderSubmitVO build = OrderSubmitVO.builder()//对应结果直接自动装填封装成对象返回
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return build;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        /////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult select(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.select(ordersPageQueryDTO);
        List<OrderVO> result = page.getResult();
        for (OrderVO results : result) {
            //获取订单id
            Long id = results.getId();
            //根据订单id查询订单明细并进行添加
            List<OrderDetail> orderDetail = orderDetailMapper.select(id);
            results.setOrderDetailList(orderDetail);
        }
        long total = page.getTotal();
        return new PageResult(total,result);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetailById(Long id) {
        OrderVO orderVO = new OrderVO();
        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailById(id);
        Orders orders = orderMapper.getOrderById(id);
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        orderMapper.cancelOrder(id);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {
        //获取订单详细多条数据
        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailById(id);
        for (OrderDetail orderDetail : orderDetails) {//循环去除并添加
            ShoppingCart shoppingCart = new ShoppingCart();//添加到购物车中
            Long currentId = BaseContext.getCurrentId();//获取当前用户id并添加
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(currentId);
            shoppingCartMapper.insert(shoppingCart);//插入到购物车内
        }
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearchOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        //下面注释的代码有所欠缺 返回数据不是太完整需要进行拷贝在进行返回
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.select(ordersPageQueryDTO);
        long total = page.getTotal();
        List<OrderVO> result = page.getResult();
        for (OrderVO orderVO : result) {
            Orders orders = orderMapper.getOrderById(orderVO.getId());
            String orderDishesStr = getOrderDishesStr(orders);
            orderVO.setOrderDishes(orderDishesStr);
        }
        return new PageResult(total,result);

        /*PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.select(ordersPageQueryDTO);
        //部分订单状态 需要返回额外的菜品信息  转换一下类型
        List<OrderVO> orderVOList = getOrderVOList(page);
        return new PageResult(page.getTotal(), orderVOList);*/

    }

 /*   //定义方法进行封装
    private List<OrderVO> getOrderVOList(Page<OrderVO> page) {
        //需要返回订单菜品信息  自定义响应结果
        List<OrderVO> orderVOList = new ArrayList<>();
        //根据传过来的page进行获取参数
        List<OrderVO> orderList = page.getResult();
        if (!CollectionUtils.isEmpty(orderList)){
            for (OrderVO orderVO : orderList) {
//                //将共同字段进行复制
//                OrderVO orderVO1 = new OrderVO();
//                BeanUtils.copyProperties(orderVO,orderVO1);
                String orderDishes = getOrderDishesStr(orderVO);
                orderVO.setOrderDishes(orderDishes);
            }
        }
        return orderVOList;
    }*/
    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
        private String getOrderDishesStr(Orders orders) {
            // 查询订单菜品详情信息（订单中的菜品和数量）
            List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailById(orders.getId());

            // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
            List<String> orderDishList = orderDetailList.stream().map(x -> {
                String orderDish = x.getName() + "*" + x.getNumber() + ";";
                return orderDish;
            }).collect(Collectors.toList());

            // 将该订单对应的所有菜品信息拼接在一起
            return String.join("", orderDishList);
        }


    /**
     * 查询订单详情
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.getOrderById(id);
        List<OrderDetail> detailList = orderDetailMapper.getOrderDetailById(id);
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(detailList);
        return orderVO;
    }

    /**
     * 接单
     * @param
     */
    @Override
    public void confirmOrder(Orders orders) {
//        Long id = ordersConfirmDTO.getId();//订单id
//        Orders orders = orderMapper.getOrderById(id);
        orders.setStatus(Orders.CONFIRMED);
        /*Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();*/
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //首先根据id查询订单判断
        Long id = ordersRejectionDTO.getId();
        Orders orders = orderMapper.getOrderById(id);
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            //判断当前订单状态  不是已接单都抛出异常
        }
      /*  //支付状态
        Integer status = orders.getStatus();
        if (status == (Orders.PAID)){
            // TODO: 2023/4/19 当前已支付需退款但不会
        }*/
        Orders orders1 = OrderVO.builder()
                .id(orders.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders1);
    }


    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .build();
        orderMapper.update(orders);
    }
    /**
     *派送订单
     */
    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);

        return orderStatisticsVO;

    }

    /**
     * 用户催单
     * @param id
     */
    public void reminder(Long id) {
        //查询订单是否存在
        Orders orders = orderMapper.getOrderById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        }
        //基于WebSocket进行实现
        Map map = new HashMap();
        map.put("tye",2);//2表示用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address*/
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //1、获取店铺的经纬度坐标
        String shopCoordinate =
                HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location =
                jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);

        //2、获取用户收货地址的经纬度坐标
        String userCoordinate =
                HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //3、路线规划
        String json = HttpClientUtil.doGet(
                "https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

}
